<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeGridProps } from '#/adapter/vxe-table';
import type { TagGroupVO } from '#/api/company/tag/model';

import { computed, onMounted, ref } from 'vue';

import { useAccess } from '@vben/access';
import { Page, useVbenDrawer, useVbenModal } from '@vben/common-ui';
import { DictEnum } from '@vben/constants';
import { useTabs } from '@vben/hooks';
import { VbenIcon } from '@vben/icons';
import { $t } from '@vben/locales';

import { Empty, Popconfirm, Segmented, Space } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  tagGroupChangeStatus,
  tagGroupInfo,
  tagGroupList,
  tagGroupRemove,
} from '#/api/company/tag';
import { ColorTag } from '#/components/dict';
import { DetailsModal } from '#/components/modal';
import { TableSwitch } from '#/components/table';

import {
  querySchema,
  tagGroupColumns,
  tagGroupDetailsSchema,
  updateCategorySchema,
} from './data';
import tagDrawer from './tag-drawer.vue';
import tagGroupModal from './tag-group-modal.vue';

const { hasAccessByCodes } = useAccess();

// 标签级别选项卡列表
const typeOptions = computed(() => {
  const options = [];
  if (hasAccessByCodes(['company:label:companyType'])) {
    options.push({
      value: 1,
      payload: { icon: 'bxs:building-house', label: '公司级别' },
    });
  }
  if (hasAccessByCodes(['company:label:personalType'])) {
    options.push({
      value: 2,
      payload: { icon: 'fa6-solid:user-tag', label: '个人级别' },
    });
  }
  return options;
});

// 标签组分级别权限
function getButtonAccess(key: string) {
  const accessMap: Record<number, Record<string, string>> = {
    1: {
      groupAdd: 'company:labelGroup:add',
      groupEdit: 'company:labelGroup:edit',
      groupRemove: 'company:labelGroup:remove',
      groupManage: 'company:label:list',
    },
    2: {
      groupAdd: 'company:labelGroupEmployee:add',
      groupEdit: 'company:labelGroupEmployee:edit',
      groupRemove: 'company:labelGroupEmployee:remove',
      groupManage: 'company:labelEmployee:list',
    },
  };

  const typeMap = accessMap[currentType.value];
  if (!typeMap) return false;

  const code = typeMap[key];
  return code ? hasAccessByCodes([code]) : false;
}

const currentType = ref(1);
const { setTabTitle } = useTabs();

function setTagTabTitle(value: number) {
  const label = typeOptions.value.find((item) => item.value === value)?.payload
    .label;
  const title = label ? ` - ${label}` : '';
  setTabTitle(`企业标签${title}`);
}

const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: querySchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
  // 处理区间选择器RangePicker时间格式 将一个字段映射为两个字段 搜索/导出会用到
  // 不需要直接删除
  // fieldMappingTime: [
  //  [
  //    'createTime',
  //    ['params[beginTime]', 'params[endTime]'],
  //    ['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59'],
  //  ],
  // ],
};

const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: false,
    // 点击行选中
    // trigger: 'row',
  },
  columns: tagGroupColumns,
  height: 'auto',
  keepSource: false,
  pagerConfig: {
    enabled: false,
  },
  expandConfig: {
    expandAll: true,
  },
  proxyConfig: {
    ajax: {
      query: async (_, formValues = {}) => {
        if (typeOptions.value.length === 0) {
          return { rows: [] };
        }

        const resp = await tagGroupList({
          ...formValues,
          type: currentType.value,
        });

        return { rows: resp };
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  // 表格全局唯一表示 保存列配置需要用到
  id: 'company-tag-group-index',
  showOverflow: false,
};

const [BasicTable, tableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents: {
    // 需要控制不同的事件 radio也会触发checkbox事件
    checkboxChange: checkBoxEvent,
    checkboxAll: checkBoxEvent,
  },
});

function checkBoxEvent() {
  // const records = tableApi.grid.getCheckboxRecords();
  // tableApi.query();
}

// 级别类型选项卡切换
async function handleTypeChange(value: number | string) {
  // 重置搜索
  await tableApi.formApi.resetForm();
  // 更新标签组分类
  updateCategorySchema(tableApi.formApi, value as number);
  setTagTabTitle(value as number);
  await tableApi.reload();
}

const [TagGroupModal, tagGroupModalApi] = useVbenModal({
  connectedComponent: tagGroupModal,
});

const [TagDrawer, drawerApi] = useVbenDrawer({
  connectedComponent: tagDrawer,
});

const [TagGroupDetailsModal, tagGroupDetailsModalApi] = useVbenModal({
  connectedComponent: DetailsModal,
});

onMounted(() => {
  setTagTabTitle(currentType.value);
});

function handleAddTagGroup() {
  tagGroupModalApi.setData({ type: currentType.value });
  tagGroupModalApi.open();
}

const tagGroupDetailsSchema_ = ref(tagGroupDetailsSchema());

function handleTagGroupPreview(row: TagGroupVO) {
  const categorySchema = tagGroupDetailsSchema_.value.find(
    (v) => v.fieldName === 'category',
  ) as DetailsModalSchema;
  if (currentType.value === 1) {
    categorySchema.dictEnum = DictEnum.COMPANY_TAG_COMPANY_CATEGORY;
  }
  if (currentType.value === 2) {
    categorySchema.dictEnum = DictEnum.COMPANY_TAG_PERSONAL_CATEGORY;
  }
  tagGroupDetailsModalApi.setData(row);
  tagGroupDetailsModalApi.open();
}

async function handleEditTagGroup(row: TagGroupVO) {
  tagGroupModalApi.setData({ id: row.id, type: currentType.value });
  tagGroupModalApi.open();
}

async function handleEditTag(row: TagGroupVO) {
  drawerApi.setData({ tagGroupId: row.id, type: currentType.value });
  drawerApi.open();
}

async function handleDeleteTagGroup(row: TagGroupVO) {
  await tagGroupRemove([row.id]);
  await tableApi.reload();
}

async function tagGroupStatusUpdate(row: TagGroupVO) {
  const data = {
    id: row.id,
    status: row.status,
  };
  await tagGroupChangeStatus(data);
}

function expandAll() {
  tableApi.grid?.setAllRowExpand(true);
}

function collapseAll() {
  tableApi.grid?.setAllRowExpand(false);
}
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable>
      <template #toolbar-actions>
        <Segmented
          v-if="typeOptions.length > 0"
          v-model:value="currentType"
          :options="typeOptions"
          block
          class="mb-2"
          @change="handleTypeChange"
        >
          <template #label="{ payload = {} }">
            <div class="flex items-center gap-1">
              <VbenIcon :icon="payload.icon" />
              <span>{{ payload.label }}</span>
            </div>
          </template>
        </Segmented>
      </template>
      <template #toolbar-tools>
        <Space>
          <a-button @click="collapseAll">
            {{ $t('pages.common.collapse') }}
          </a-button>
          <a-button @click="expandAll">
            {{ $t('pages.common.expand') }}
          </a-button>
          <a-button
            type="primary"
            v-if="getButtonAccess('groupAdd') && typeOptions.length > 0"
            @click="handleAddTagGroup"
          >
            {{ $t('pages.common.add') }}标签组
          </a-button>
        </Space>
      </template>
      <template #expandContent="{ row }">
        <div v-if="row.labels.length > 0" class="flex flex-wrap gap-2 p-4">
          <ColorTag
            v-for="tag in row.labels"
            :key="tag.id"
            :color="tag.listClass"
            :label="tag.name"
            :disabled="tag.status === '1'"
            icon="gravity-ui:tag"
          />
        </div>
        <div v-else class="p-5">
          <Empty description="暂无标签" />
        </div>
      </template>
      <template #status="{ row }">
        <TableSwitch
          v-model:value="row.status"
          :api="() => tagGroupStatusUpdate(row)"
          :disabled="!getButtonAccess('groupEdit')"
          @reload="tableApi.reload()"
        />
      </template>
      <template #action="{ row }">
        <Space>
          <ghost-button
            v-access:code="['company:labelGroup:query']"
            @click="handleTagGroupPreview(row)"
          >
            详情
          </ghost-button>
          <ghost-button
            v-if="getButtonAccess('groupEdit')"
            @click="handleEditTagGroup(row)"
          >
            编辑
          </ghost-button>
          <ghost-button
            v-if="getButtonAccess('groupManage')"
            @click="handleEditTag(row)"
          >
            管理标签
          </ghost-button>
          <Popconfirm
            placement="left"
            :title="
              row.labels?.length > 0
                ? `该标签组里含多个标签，确认删除标签组？`
                : `确认删除此标签组？`
            "
            @confirm="handleDeleteTagGroup(row)"
          >
            <ghost-button
              danger
              v-if="getButtonAccess('groupRemove')"
              @click.stop=""
            >
              删除组
            </ghost-button>
          </Popconfirm>
        </Space>
      </template>
    </BasicTable>
    <TagGroupModal @reload="tableApi.reload()" />
    <TagDrawer @reload="tableApi.reload()" />
    <TagGroupDetailsModal
      :columns="tagGroupDetailsSchema_"
      :api="tagGroupInfo"
      :width="800"
    >
      <template #labels="{ info }">
        <div v-if="info.labels.length > 0" class="flex flex-wrap gap-1">
          <ColorTag
            v-for="tag in info.labels"
            :key="tag.id"
            :color="tag.listClass"
            :label="tag.name"
            :disabled="tag.status === '1'"
            icon="gravity-ui:tag"
          />
        </div>
        <div v-else class="p-5">
          <Empty description="暂无标签" />
        </div>
      </template>
    </TagGroupDetailsModal>
  </Page>
</template>
